package com.lumm.controller;

import com.lumm.model.ResponseObject;
import com.lumm.model.Staff;
import com.lumm.model.User;
import com.lumm.services.AdminService;
import com.lumm.services.UserService;
import com.lumm.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/admin")
public class UserManageController {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "getUserList", method = RequestMethod.GET)
    public String getUserList(
            @RequestParam(value = "offset", required = false, defaultValue = "0") int offset,
            @RequestParam(value = "count", required = false, defaultValue = "20") int count,
            HttpSession session,
            Model model
    ) {
        Staff staff = (Staff) session.getAttribute("staff");
        if (staff.getType() != 0)
            return "redirect:/admin";
        model.addAttribute("userList", userService.getUserList(offset, count));
        return "admin/htmlGenerators/generateUserList";
    }

    @ResponseBody
    @RequestMapping(value = "getUserCount", method = RequestMethod.GET)
    public ResponseObject getUserCount(
            HttpSession session
    ) {
        Staff staff = (Staff) session.getAttribute("staff");
        if (staff.getType() != 0)
            return new ResponseObject(1, -2);

        return new ResponseObject(1, 1, userService.getUserCount());
    }

    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public String addUser(
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "gender", required = true) String gender,
            @RequestParam(value = "email", required = true) String email,
            @RequestParam(value = "maritalStatus", required = true) short maritalStatus,
            @RequestParam(value = "phoneNum", required = true) String phoneNum,
            @RequestParam(value = "birthday",required = true) String birthday,
            HttpServletResponse httpServletResponse,
            HttpSession session,
            Model model
    ) {
        Staff staff = (Staff) session.getAttribute("staff");
        if (staff.getType() != 0)
            return "redirect:/admin";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date birthdayDate;

        try {
            birthdayDate = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
            model.addAttribute("msg","参数错误！");
            return "alert";
        }
        int userId=userService.addNewUser(email,gender,name,birthdayDate,phoneNum,maritalStatus);

        if (userId==2){
            model.addAttribute("msg","邮箱已存在！");
            return "alert";
        }

        List<User> users=new ArrayList<>();
        users.add(userService.querybyUserId(userId));

        model.addAttribute("userList", users);

        return "admin/htmlGenerators/generateUserList";
    }


    @ResponseBody
    @RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
    public ResponseObject updateUserInfo(
            @RequestParam(value = "userId",required = true) int userId,
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "gender", required = true) String gender,
            @RequestParam(value = "email", required = true) String email,
            @RequestParam(value = "maritalStatus", required = true) short maritalStatus,
            @RequestParam(value = "phoneNum", required = true) String phoneNum,
            @RequestParam(value = "birthday",required = true) String birthday,
            HttpSession session
    ) {
        Staff staff = (Staff) session.getAttribute("staff");
        if (staff.getType() != 0)
            return new ResponseObject(0,-2);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date birthdayDate;

        try {
            birthdayDate = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResponseObject(0,2);
        }

        int status = userService.updateUserInfo(userId,gender,name,birthdayDate,phoneNum,maritalStatus);

        if (status==0)
            return new ResponseObject(0,3);

        return new ResponseObject(1,1,userService.querybyUserId(userId));
    }

    @ResponseBody
    @RequestMapping(value = "deleteUser", method = RequestMethod.GET)
    public ResponseObject deleteUser(
            @RequestParam(value = "userId", required = true) int userId,
            HttpSession session
    ) {
        Staff staff = (Staff) session.getAttribute("staff");
        if (staff.getType() != 0)
            return new ResponseObject(1,-2);
        return new ResponseObject(1,userService.deleteUser(userId));
    }

    @RequestMapping(value="importUsers",method=RequestMethod.POST)
    public String importUsers(MultipartFile file, HttpServletRequest request,Model model) throws IOException {

        String path = request.getSession().getServletContext().getRealPath("upload")+"/temp";

        System.out.println(path);

        File file1=FileUtil.transMultipartFileToFile(file,path);


        List<User> users=userService.importUserList(file1);

        if (users==null||users.size()==0){
            model.addAttribute("msg","导入失败！");
            return "alert";
        }

        model.addAttribute("msg","<script>alert('已导入"+users.size()+"个用户！');</script>");

        model.addAttribute("userList",users);

        //    return new ResponseObject(0,successCount);

        return "admin/htmlGenerators/generateUserList";
    }


}
